package common;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class UDPTools_1 {
	
	static int bufferSize = 1000;
	
	// this function may be used at the Front end level to send UDP message to the replica leader
	// it may also be used at the level of replica leader to send UDP message to the replica
	public  String sendReceiveUDP(int receiverUDPPort,String receiver,String receiverRole,   String senderRole, String  messageOut) {

		DatagramSocket serverSocket = null;
		InetAddress receiverAddress;
		byte[] bufferOut = new byte[bufferSize];
		byte[] bufferIn = new byte[bufferSize];
		String result = null;
		
		try {
			synchronized(receiverRole){
				receiverAddress = InetAddress.getByName(receiver);
	
				serverSocket = new DatagramSocket();
				bufferOut = messageOut.getBytes();
				DatagramPacket request = new DatagramPacket(bufferOut,bufferOut.length, receiverAddress, receiverUDPPort);
				serverSocket.send(request);
				
				//receive the acknowledge
				DatagramPacket acknowledge = new DatagramPacket(bufferIn,	bufferIn.length,receiverAddress, receiverUDPPort);
				serverSocket.receive(acknowledge);
				String acknowledgeResult = (new String(acknowledge.getData())).trim();
				
				CommonTools.writeLog(
						senderRole,
						senderRole,
						"An acknowledge was received:"
						+ acknowledgeResult, "replica");		
				
								
				bufferIn = new byte[bufferSize];
				
				//receive the response
				DatagramPacket reply = new DatagramPacket(bufferIn,	bufferIn.length,receiverAddress, receiverUDPPort);
				serverSocket.receive(reply);
				result = (new String(reply.getData())).trim();
				bufferOut = new byte[bufferSize];
				bufferIn = new byte[bufferSize];
			}

		} catch (UnknownHostException e) {

			e.printStackTrace();
			
		} catch (Exception e) {

			e.printStackTrace();
		}
		// add close socket
		finally {
			if (serverSocket != null)
				serverSocket.close();
		}
		return result;
	}
	
	

}
